package org.statewalker.fsm.providers;

import java.util.LinkedHashSet;
import java.util.Set;


public class CompositeFsmTransitionsRegistry implements IFsmTransitionsRegistry {

    private Set<FsmTransitionsRegistry> fSet = new LinkedHashSet<FsmTransitionsRegistry>();

    public synchronized void addRegistry(FsmTransitionsRegistry registry) {
        LinkedHashSet<FsmTransitionsRegistry> set = new LinkedHashSet<FsmTransitionsRegistry>(
            fSet);
        set.add(registry);
        fSet = set;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!(obj instanceof CompositeFsmTransitionsRegistry))
            return false;
        CompositeFsmTransitionsRegistry o = (CompositeFsmTransitionsRegistry) obj;
        return fSet.equals(o.fSet);
    }

    /**
     * @see org.statewalker.fsm.providers.FsmTransitionsRegistry#getDefaultTransition(java.lang.Object,
     *      java.lang.Object)
     */
    public String getDefaultTransition(String parent, String event) {
        String result = null;
        Set<FsmTransitionsRegistry> set = fSet;
        for (FsmTransitionsRegistry registry : set) {
            result = registry.getDefaultTransition(parent, event);
            if (result != null)
                break;
        }
        return result;
    }

    /**
     * @see org.statewalker.fsm.providers.IFsmTransitionsRegistry#getParentEventKey(java.lang.String)
     */
    public String getParentEventKey(String event) {
        String result = null;
        Set<FsmTransitionsRegistry> set = fSet;
        for (FsmTransitionsRegistry registry : set) {
            result = registry.getParentEventKey(event);
            if (result != null)
                break;
        }
        return result;
    }

    /**
     * @param parent
     * @param from
     * @param event
     * @return
     */
    public String getTransition(String parent, String from, String event) {
        String result = null;
        Set<FsmTransitionsRegistry> set = fSet;
        for (FsmTransitionsRegistry registry : set) {
            result = registry.getTransition(parent, from, event);
            if (result != null)
                break;
        }
        return result;
    }

    @Override
    public int hashCode() {
        return fSet.hashCode();
    }

    /**
     * @param registry
     */
    public synchronized void removeRegistry(FsmTransitionsRegistry registry) {
        LinkedHashSet<FsmTransitionsRegistry> set = new LinkedHashSet<FsmTransitionsRegistry>(
            fSet);
        if (set.remove(registry)) {
            fSet = set;
        }
    }

    @Override
    public String toString() {
        return fSet.toString();
    }

}
